package com.dongrj.framework.web.utils;

import org.slf4j.Logger;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.client.WebClient;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.function.Consumer;

/**
 * @author dongrongjun
 * @date 2020/08/07
 */
public final class WebClientUtils {

    public static <Param> Mono<String> post(Logger logger, WebClient webClient, String uri, Param param) {
        return post(logger, webClient, uri, param, WebClientUtils::addHeaders);
    }

    public static <Param> Mono<String> post(Logger logger, WebClient webClient, String uri, Param param, Consumer<HttpHeaders> headers) {
        return webClient.post()
                .uri(URI.create(uri))
                .headers(headers)
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(param), param.getClass())
                .retrieve()
                .bodyToMono(String.class);
    }

    public static <Param> Mono<String> post1(Logger logger, WebClient webClient, String uri, Param param, Consumer<HttpHeaders> headers, Class tClass) {
        return webClient.post()
                .uri(uri)
                .contentType(MediaType.APPLICATION_JSON)
                .body(Mono.just(param), param.getClass())
                .exchangeToMono(response -> {
                    if (response.statusCode().equals(HttpStatus.OK)) {
                        return response.bodyToMono(String.class);
                    } else if (response.statusCode().is4xxClientError()) {
                        return Mono.just("Error response");
                    } else {
                        return response.createException().flatMap(Mono::error);
                    }
                });
    }


    public static Mono<String> post(Logger logger, WebClient webClient, String uri, String jsonParam) {
        return webClient.post().uri(uriBuilder -> uriBuilder.path(uri).queryParam("response", jsonParam).build()).retrieve().bodyToMono(String.class);
    }

    private static void addHeaders(HttpHeaders headers) {

    }

}